package live.ifox.stage;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

import live.ifox.base.BaseRestActivity;
import live.ifox.factory.Entry;
import live.ifox.factory.ID;
import live.ifox.factory.StaffInfo;
import live.ifox.factory.Url;
import live.ifox.helper.AdapterHelper;
import live.ifox.helper.CustomProfile;

public class PositionActivity extends BaseRestActivity {
    SwipeRefreshLayout swipeLayout;
    ListView listView;
    EditText in_search;
    JSONArray array;
    String label;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_position);
        actionBar.setTitle(R.string.position);

        entry = Entry.Position;
        baseUrl = Url.Position;
        in_search = findViewById(R.id.in_search);
        listView = findViewById(R.id.listView);
        registerForContextMenu(listView);
        swipeLayout = findViewById(R.id.swipeLayout);

        swipeLayout.setOnRefreshListener(() -> {
            swipeLayout.setRefreshing(false);
            updateView();
        });

        in_search.setOnEditorActionListener(
                //当actionId == XX_GO 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                (v, actionId, event) -> {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                            (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode())) {
                        label = in_search.getText().toString();
                        updateView();
                    }
                    return false;   //true，保留软键盘; false，隐藏软键盘
                }
        );
    }

    void updateView() {
        if (label != null && !label.isEmpty())
            httpGet(baseUrl + "search/" + label);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, ID.ACTION_ADD, 0, "添加...");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case ID.ACTION_ADD:
                startActivity(new Intent(this,
                        PositionEditor.class));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, ID.ACTION_EDIT, 0, "编辑...");
        menu.add(0, ID.ACTION_REMOVE, 1, "删除");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (array.isEmpty())
            return false;

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        JSONObject object = array.getJSONObject(position);

        switch (item.getItemId()) {
            case ID.ACTION_EDIT:
                return do_editItem(object);
            case ID.ACTION_REMOVE:
                return do_removeItem(object);
        }
        return super.onContextItemSelected(item);
    }

    boolean do_editItem(JSONObject object) {
        int id = object.getIntValue("id");
        String topic = object.getString("topic");
        String label = object.getString("label");
        if (id == 0 || topic.isEmpty() || label.isEmpty())
            return false;

        Intent intent = new Intent(this,
                PositionEditor.class);
        intent.putExtra("id", id);
        intent.putExtra("topic", topic);
        intent.putExtra("label", label);
        startActivityForResult(intent, ID.POSITION_EDITOR);
        return true;
    }

    boolean do_removeItem(JSONObject object) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确定操作").setMessage("确定删除吗？");
        builder.setPositiveButton(R.string.sure,
                (paramAnonymousDialogInterface, paramAnonymousInt) ->
                {
                    int id = object.getIntValue("id");
                    if (id > 0)
                        httpGet(baseUrl + "remove/" + id);
                });

        builder.setNegativeButton(R.string.cancel,
                (paramAnonymousDialogInterface, paramAnonymousInt) -> {
                });

        builder.create().show();
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ID.RESULT_DONE) {
            updateView();
        }
    }

    @Override
    public void processReply(JSONObject rootObject) {
        array = AdapterHelper.verifyObject(rootObject, entry);
        if (array.isEmpty()) {
            listView.setAdapter(null);
            return;
        }

        List<String> items = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            items.add(object.getString("topic") + "  " +
                    object.getString("label"));
        }

        ArrayAdapter<String> adapter = AdapterHelper.getArrayAdapter(this, items);
        listView.setAdapter(adapter);
    }
}
